package cn.wolfcode.p2p.base.service.impl;

import cn.wolfcode.p2p.base.domain.MailVerify;
import cn.wolfcode.p2p.base.service.IEmailService;
import cn.wolfcode.p2p.base.service.IMailVarifyService;
import cn.wolfcode.p2p.base.util.Constants;
import cn.wolfcode.p2p.base.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

@Service@Transactional
public class EmailServiceImpl implements IEmailService {

    @Autowired
    private IMailVarifyService mailVarifyService;

    @Value("${email.applicationUrl}")
    private String applicationUrl;

    /**
     * 发送eamil邮箱认证
     * @param email
     */
    @Override
    public void sendEmail(String email) {
        //生成UUID
        String uuid = UUID.randomUUID().toString();
        //拼接邮件的内容 发送邮件
        StringBuilder msg = new StringBuilder(50);
        msg.append("感谢注册p2p学贷网站,这是一封注册邮件,点击<a href='").append(applicationUrl)
        .append("?key=").append(uuid).append("'>这里</a>完成认证,邮件有效期为")
        .append(Constants.DEFAULT_TIME_DAY).append("天");
        //模拟邮件发送
        System.out.println(msg);
        //把邮件地址 用户ID 发送时间 UUID保存到数据库中
        MailVerify mail = new MailVerify();
        mail.setSendTime(new Date());
        mail.setEmail(email);
        mail.setUuid(uuid);
        mail.setUserId(UserContext.getCurrent().getId());
        mailVarifyService.save(mail);
    }
}
